package com.chenye.design.state;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @Auther:chenye
 * @Data:2018/11/1
 * @Description:状态机管理类
 */
public class VoteManager {
    private VoteState voteState;

    private static final ConcurrentHashMap<String,String> voteMap = new ConcurrentHashMap();
    private static final ConcurrentHashMap<String,Integer> voteCountMap = new ConcurrentHashMap();
    private static final ConcurrentHashMap<String,String> blackNameMap = new ConcurrentHashMap<>();

    public void vote(String userName,String voteItem){
        if(userName == null || voteItem == null){
            throw new RuntimeException("userName，voteItem 不能为空");
        }
        String blackName = blackNameMap.get(userName);
        if (blackName != null) {
            throw new RuntimeException(userName+"已经进入黑名单");
        }

        String votedItem = voteMap.get(userName);
        if (votedItem == null) {
            voteMap.put(userName,voteItem);
        }
        Integer count = voteCountMap.get(voteItem);
        if(count == null){
            count = 0;
        }
        count++;
        voteCountMap.put(voteItem,count);
        // 正常投票
        if (count <= 1) {
            voteState = new NormalVoteState();
        }
        // 重复投票
        if(count > 1 && count <= 5){
            voteState = new RepeatVoteState();
        }
        // 恶意刷票
        if (count > 5 && count <= 10) {
            voteState = new SpiteVoteState();
        }
        // 加入和名单
        if(count > 10){
            voteState = new BlackVoteState();
        }

        voteState.doVote(this,userName,voteItem);
    }

    public ConcurrentHashMap<String,String> getBlackNameMap(){
        return blackNameMap;
    }

    public static void main(String[] args) {
        VoteManager manager = new VoteManager();
        for (int count = 0; count < 12; count++) {
            manager.vote("testName","testItem");
        }
    }
}
